package com.nmgs.config;

/**
 * 启用跨域配置
 * 编写SpringMVCConfig类使用FilterConfig中的配置
 *
 * @author Administrator
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.Resource;

@SuppressWarnings("deprecation")
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Resource
    private FilterConfig filterconfig;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /* swagger配置 */
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 设置拦截类
        System.out.println("进来了拦截器========");
        registry.addInterceptor(filterconfig)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/autolaneTable/**",
                        "/yzxCameraTable/**",
                        "/nameTable/**",
                        "/selectData/**",
                        "/setupTable/**",
                        "/yzxKeyTable/**",
                        "/serverTable/**",
                        "/yzxSipphoneTable/**",
                        "/yzx/**"
                );
    }

    /**
     * 跨越配置
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 设置容许跨域请求的域名
        config.addAllowedOriginPattern("*");
        // 设置容许的方法
        config.addAllowedMethod("*");
        // 容许任何头
        config.addAllowedHeader("*");
        config.addExposedHeader("token");
        //是否支持cookie跨域
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }
}